<?php
// $Id$

/**
 * Controller_Admin_System 控制器
 */
class Controller_Admin_System extends Controller_Abstract
{	
	function IntToStr($v)
	{
		return (string)"'".$v."'";
	}
	/**
	 * 代理下级设置
	 */
	function actionsetting()
	{
		if($_SESSION['acct']['acclevel'] <= 2)
		{
			if($this->_context->isGET())
			{
				$vip = Acctsetting::find('agent_id = ? ',$_SESSION['acct']['id'])->asArray()->getOne();
				$this->_view['setting'] = $vip;
			}else{
				$vipmoney = trim($this->_context->vipmoney);
				if (!$vipmoney)
				{
					return $this->error('金额必须填写');
				}else{
					$vip = Acctsetting::find('agent_id = ? ',$_SESSION['acct']['id'])->getOne();
					if (!$vip->id())
					{
						$vip = new Acctsetting();
					}
					$vip->admin_id = $_SESSION['acct']['admin_id'];
					$vip->agent_id = $_SESSION['acct']['id'];
					$vip->vipmoney = floatval($vipmoney);
					$vip->save();
					return $this->success('修改成功');	
				}
			}
		}else{
			exit('权限不够');
		}
		
	}
	/**
	 * 代理设置短信内容
	 */
	function actionagentsettxt()
	{
		if($_SESSION['acct']['acclevel'] == 2)
		{
			if($this->_context->isGET())
			{
				
			}else{
				$smsmsg = trim($this->_context->smsmsg);
				$smstype = intval($this->_context->smstype);
				if(mb_strlen($smsmsg,'utf-8')>=20 && $smstype == 0)
				{
					return $this->error('内容长度必须低于20字符');
				}
			    
				$smssign = trim($this->_context->smssign);
				$smssign = str_replace('【', '', $smssign);
				$smssign = str_replace('】', '', $smssign);
			    if(mb_strlen($smssign,'utf-8')>=10)
				{
					return $this->error('签名长度必须低于10字符');
				}
				if (!$smsmsg)
				{
					return $this->error('内容必须填写');
				}else{
					$acct = acct::find('id = ?',$_SESSION['acct']['id'])->getOne();
					if($acct->id())
					{
						$acct->smsmsg = $smsmsg;
						$acct->smssign = '【'.$smssign.'】';
						$acct->smstype = $smstype;
						$acct->smsflag = 0;
						$acct->save(0,'update');
						$_SESSION['acct']['smsflag'] = 0;
						$_SESSION['acct']['smsmsg'] = $smsmsg;
						$_SESSION['acct']['smssign'] = $acct->smssign;
						
						return $this->success('内容修改成功,请等待管理审核内容!');
					}else{
						return $this->error('您当前的短信开关未打开,请联系上级!');
					}
				}
			}
		}else{
			exit('权限不够');
		}
	}
	/**
	 * 设置短信地址
	 */
	function actionSetSmsUrl()
	{
		if($_SESSION['acct']['acclevel'] == 0)
		{
			if($this->_context->isGET())
			{
				
			}else{
				
				$smsUrl = trim($this->_context->smsurl);
				$smsbalance = ($this->_context->smsbalance);
				$smsreturn = $this->_context->smsreturn;
				if (!$smsUrl)
				{
					return $this->error('必须填写地址');
				}else{
					$acct = Acct::find('admin_id = ? or id = ?',$_SESSION['acct']['id'],$_SESSION['acct']['id'])->getAll();
					foreach($acct as $k=>$item)
					{
						$item->changeProps(array('smsurl'=>$smsUrl,'smsbalance'=>$smsbalance,'smsreturn'=>$smsreturn));
						$item->save(0,'update');
					}
					$_SESSION['acct']['smsurl'] = $smsUrl;
					$_SESSION['acct']['smsbalance'] = $smsbalance;
					$_SESSION['acct']['smsreturn'] = $smsreturn;
					return $this->success('修改成功');
				}
			}
		}else{
			exit('无权限');
		}
	}
	function _format_appendSql()
	{
		if (isset($_SESSION['acct']))
		{
			if ($_SESSION['acct']['admin_id'] == -1 && $_SESSION['acct']['agent_id'] == -1)
			{
			//为管理
				//$append['']
				$append['admin_id'] = $_SESSION['acct']['id'];
				
			}else
			{
				$append['admin_id'] = $_SESSION['acct']['admin_id'];
				$append['agent_id'] = array_merge(Acct::_get_have_acctid($_SESSION['acct']['id'], $_SESSION['acct']['admin_id']));
				
				$append['agent_id'][] = $_SESSION['acct']['id'];
			}
		}
		return $append;
	}
	function actionhangup()
	{
		$id = intval($this->_context->id);
		$call = Calllist::find('id = ?',$id)->getOne();
		if($call->id())
		{
			$call->hangup = 1;
			try {
			$call->save();
			return $this->success('挂断成功');
			} catch (Exception $e) {
			return $this->error($e->getmessage());
			}
			
		}else
		{
			return $this->error('不存在数据');
		}
	}
	function actioncalllist()
	{
		
		if ($_SESSION['acct']['admin_id'] == -1 && $_SESSION['acct']['agent_id'] == -1)
			{
				//$acctname['acct'] = 
				$acctArr = null;
			}else {
				$append['agent_id'] = array_merge(Acct::_get_have_acctid($_SESSION['acct']['id'], $_SESSION['acct']['admin_id']));
				
				$append['agent_id'][] = $_SESSION['acct']['id'];
				$userArr = Acctuser::find($append)->setColumns('acctname')->asArray()->getAll();
				
				$userArr = Helper_Array::toHashmap($userArr, 'acctname');
				$acctArr['acct'] = array_map(array($this,'IntToStr'),array_keys($userArr));
				
				
			}
			
		$this->union_table = Calllist::meta();
		$this->lists($acctArr);
	}
	function actionlog()
	{
		$this->union_table = Syslog::meta();
		$this->lists($this->_format_appendSql());
	}
	function actionpartcode()
	{
		$this->union_table = mobileparycode::meta();
		$this->lists();
	}
	function actionsiponline()
	{
		//获取搜索参数
		$this->get_param();
		//初始化分页信息
		$this->_format_page_info();
		$this->union_table = Sipbindten::meta();
		//关联表
		//$this->union_table = $union_table;
		//if (!is_null($append_data))$this->param = array_merge($this->param,$append_data);
		
		//$dis_param = new helper_disposeparam($this->param);
		//$_SESSION['lastsql'] = $dis_param->getsql();//OUT PUT用
		$obj = call_user_func_array(array($this->union_table,'find'), array("ipaddr<>''"));
		$item = $obj->limitPage($this->curr_page,$this->page_size)
					->order(' '.$this->orderkey.' '.$this->ordertype)
					->fetchPagination($this->pagination)
					->getall();
		$this->_view['item'] = $item;
		$this->_view['pagination'] = $this->pagination;	
		$this->_view['orderField'] = $this->orderkey;
		$this->_view['orderDirection'] = $this->ordertype;
	}
	function actionbackdel()
	{
		$file = $this->_context->get('filename');
			$appIni = Q::ini('appini/databack');
			$tableName = $appIni['tablename'];
			$path = $appIni['bakpath'];
			$fileName =$path.$file;
			//@unlink($fileName);
			return $this->success('删除成功');
	}
	function actiondoback()
	{
			$file = $this->_context->get('filename');
			$file = str_replace('/', '', $file);
			$file = str_replace('\\', '', $file);
			
			$appIni = Q::ini('appini/databack');
			$tableName = $appIni['tablename'];
			$path = $appIni['bakpath'];
			$fileName =$path.$file;
			$filetype = strtolower( array_pop( explode( ".", $fileName ) ) );
				if ( $filetype == "gz" )
				{
						exec( "gzip -d ".$fileName );
						$fileName = str_replace( ".gz", "", $fileName );
				}
			global $root_dir;
		
			$config = Helper_YAML::load($root_dir.'/config/database.yaml');
			$database = $config['devel'];
			if ( $database['password'] == "" )
			{//| gzip
					exec( "mysql -h  {$database['host']} -u".$database['login']."  ".$database['database']."  < ".$fileName );
			}
			else
			{
					exec( "mysql -h {$database['host']} -u".$database['login']." -p".$database['password']."  ".$database['database']." < ".$fileName );
			}
			//exit("mysql -h   -u".$database['login']." -p".$database['password']."  ".$database['database']." < ".$fileName);
			return $this->success('数据恢复成功');
	}
	function actiondatabak()
	{
		if ($this->_context->isGET())
		{
			$appIni = Q::ini('appini/databack');
			$tableName = $appIni['tablename'];
			$path = $appIni['bakpath'];
			$this->_view['path'] = $path;
		}else
		{
			$appIni = Q::ini('appini/databack');
			$tableName = $appIni['tablename'];
			$path = $appIni['bakpath'];
			$fileName =$path.date('Y-m-d_H-i-s',time()).'_voip.sql.gz';
			global $root_dir;
		
			$config = Helper_YAML::load($root_dir.'/config/database.yaml');
			$database = $config['devel'];
			if ( $database['password'] == "" )
			{//| gzip
					exec( "mysqldump   -u".$database['login']."  ".$database['database']." {$tableName}  | gzip >".$fileName );
			}
			else
			{
					exec( "mysqldump   -u".$database['login']." -p".$database['password']."  ".$database['database']."  {$tableName} | gzip  >".$fileName );
			}
			
			return $this->success('备份成功');
		}
	}
	
	function actiontaobaolog()
	{
	    $this->union_table = Taobaocard::meta();
		$this->lists();
	}
	
	function actiontaobaoset()
	{
		$acct = Acct::find('id = ?',$_SESSION['acct']['id'])->getOne();
			
		if($this->_context->isPOST())
		{
			$flag = intval($this->_context->flag);
			$tbtoken = trim($this->_context->tbtoken);
				    $acct->buyer_nick = '';
					$acct->taobao_flag = $flag;
					//$acct->tbtoken = $tbtoken;
					$acct->save(0,'update');
					return $this->success('修改成功');
			
		}
		$this->_view['acct']=$acct;
	}
	//submitfilter
	function actionfiltercall()
	{
	    $this->union_table = Submitfilter::meta();
		$this->lists();
	}
	function actionfiltercalldel()
	{
	    Syslog::logs('删除过滤帐号:'.$this->_context->ids);
	    $this->union_table = Submitfilter::meta();
	    $this->delete(array('id'=>$this->_context->ids));
	}
	function actionaddfilter()
	{
		$this->union_table = Submitfilter::meta();
		$handle = new helper_autoinsert($this->union_table);
		$form = new Form_system_addfilter(url('system/addfilter'));
		
		$result = $handle->add($form, 'id', $_GET);
		if ($this->_context->isGET())
		{
			$this->_view['form'] = $result;
			$this->_viewname = '../form/add';
		}else {
			Syslog::logs('添加过滤账号:'.$_POST['acctname']);
			return call_user_func_array(array($this,$handle->status),array($result));
		}
	}
	function actionfenliu()
	{
		$obj = Systemfenliu::find('k = ?','218.246.196.88')->getOne();
			
		if($this->_context->isPOST())
		{
			$v = intval($this->_context->v);
			$obj->v = $v;
			$obj->save(0,'update');
			return $this->success('修改成功');
		}
		$this->_view['obj'] = $obj;
	}
	function actionserverhostdel()
	{
		$this->union_table = Serverhost::meta();
		$this->delete(array('id'=>($this->_context->ids)));
	}
	function actionserverhost()
	{
		$this->union_table = Serverhost::meta();
		$this->lists();
	}
	function actionserverhostadd()
	{
		$this->union_table = Serverhost::meta();
		//ini_set('allow_call_time_pass_reference', true); //开启引用？
		$handle = new helper_autoinsert($this->union_table);
		$form = new Form_systemserverhost_add(url($this->_context->controller_name.'/'.$this->_context->action_name));
		$result = $handle->add($form, 'id',$_GET);
		
		if ($this->_context->isGET())
		{
				
				
			//$result->element('agent_id')->value = Acct::get_curId();
				
			$this->_view['form'] = $result;
			$this->_viewname = '../form/add';
		}else {
			
			return call_user_func_array(array($this,$handle->status),array($result));
		}
	}
	function actioncleanuser()
	{
	    if($this->_context->isPOST())
	    {
	        $mobile = trim($this->_context->acctname);
	        $rernd = trim($this->_context->mobilecode);
    	     if(!Helper_Param::_call($mobile))
    	    {
    	        $result = ('号码不正确');
    	        return $this->success($result);
    	    }else if(!$rernd)
    	    {
    	    	$result = ('验证码为空');
    	    	return $this->success($result);
    	    }
    	    else{
    	        $acctuser = Acctuser::find('acctname = ?',$mobile)->getOne();
    	        if(!$acctuser->id())
    	        {
    	            $result = ('用户不存在');
    	        }else if($acctuser->agent_id == $_SESSION['acct']['id'])
    	        {
    	            $result = ('已经是您下属用户!');
    	        }
        	    if(!isset($_SESSION['cleanuser'][$mobile]['sendtime']) || !isset($_SESSION['cleanuser'][$mobile]['rnd']) || !$_SESSION['cleanuser'][$mobile]['rnd'])
    	        {
    	            $result = ('请先获取短信验证码');
    	        }
    	        $rnd = $_SESSION['cleanuser'][$mobile]['rnd'];
    	        Helper_Common::log($mobile.' input mobile code:'.$rernd.' session:'.$rnd);
    	        if($rernd == $rnd)
    	        {
        	        try {
        			Acctuser::meta()->deleteWhere('id = ?',$acctuser->id);
        			$result = '数据清除成功';
        			Syslog::logs('清除用户:'.$mobile);
        			} catch (Exception $e) {
        			$result = '数据清除失败'; //数据出错
        			}
        			unset($_SESSION['cleanuser'][$mobile]);
    	        }else{
    	            $result = '验证码输入错误';
    	            unset($_SESSION['cleanuser'][$mobile]);
    	        }
    	        return $this->success($result);
    	        exit();
    	    }
	    }
	}
	function actioncleanusertomobile()
	{
	    $mobile = trim($this->_context->mobile);
	    if(!Helper_Param::_call($mobile))
	    {
	        exit('号码不正确');
	    }else{
	        $acctuser = Acctuser::find('acctname = ?',$mobile)->getOne();
	        if(!$acctuser->id())
	        {
	            exit('用户不存在');
	        }else if($acctuser->agent_id == $_SESSION['acct']['id'])
	        {
	            exit('已经是您下属用户!');
	        }
	        if(isset($_SESSION['cleanuser'][$mobile]['sendtime']) && time() - $_SESSION['cleanuser'][$mobile]['sendtime']<60)
	        {
	            exit('60秒内不能重新发送');
	        }
	        $rnd = rand(100000, 999999);
	        $_SESSION['cleanuser'][$mobile]['rnd'] = $rnd;
	        $_SESSION['cleanuser'][$mobile]['sendtime'] = time();
	        Helper_Common::log('send '.$mobile.' mobile code:'.$rnd);
	        //try {
				//send msg
				if($acctuser->agent->smsurl  && $acctuser->agent->smsflag)
				{
					$yu = $acctuser->balance ;
					$msg = $acctuser->acctname.",您此次清除用户数据的操作验证码为:".$rnd.",请尽快使用.";
					$msglength = mb_strlen($msg,'UTF-8');
					$msg = urlencode($msg);
					$url = str_replace('%m%', $mobile, $acctuser->agent->smsurl);
					$url = str_replace('%s%', $msg, $url);
					$result = Helper_Common::cget($url);
					QLog::log('smssend:'.$url.'|'.$result);
					$result = iconv("GB2312","UTF-8",$result);
					QDB::getConn()->execute("call smscost({$acctuser->agent->id},0.01)");
				}
			
			//} catch (Exception $e) {
				//return false;
			//	exit('短信发送失败');
			//}
			exit('短信发送成功,请注意查收!');
	    }
	}
	/**
	 * 延迟扣费记录
	 */
	function actionvipmoneylog()
	{
		$this->union_table = Viplog::meta();
		$agent_list = Acct::_get_arrayinfo();
		$this->_view['agent_list'] = $agent_list;
		$param = $this->_format_appendSql();
		if(isset($_POST['agent_id']) && isset($param['agent_id']) && in_array(intval($this->_context->agent_id), $param['agent_id']))
		{
			//if()
				$param['agent_id'] = intval($this->_context->agent_id);
		}
		$this->lists($param);
		
	}
	
	function actionwebcalllog()
	{
	    $this->union_table = Webcalllog::meta();
	    $this->lists();
	}
	
	
	
	
	function actioncalltop()
	{
	    
	    $sql = "select count(id) as num,acct from voip.webcalllog where created>=".(strtotime(date('Y-m-d')))." group by acct  order by num desc limit 100 ";
	    $data = QDB::getConn()->execute($sql)->fetchAll();
	    $this->_view['data']=$data;
	}
}


